package xyz.scootaloo.oj.offer

import org.junit.Test
import java.lang.StringBuilder

/**
 * @author flutterdash@qq.com
 * @since 2021/4/11 21:37
 */
class P46 {

    private fun permutation(s: String): Array<String> {
        val res = ArrayList<String>()
        partition(s, 0, StringBuilder(), res)
        return res.toArray(arrayOf())
    }

    private fun partition(str: String, pos: Int, cache: StringBuilder, res: ArrayList<String>) {
        if (pos >= str.length) {
            res.add(cache.toString())
            return
        }
        // 移动一格
        cache.append(mapToChar(str[pos]))
        partition(str, pos + 1, cache, res)
        cache.setLength(pos)
        // 尝试移动第二格
        if (pos < str.length - 1) {
            val twoDigit = mapToChar(str[pos], str[pos + 1])
            if (twoDigit != null) {
                cache.append(twoDigit)
                partition(str, pos + 2, cache, res)
                cache.setLength(pos)
            }
        }
    }

    private fun mapToChar(num: Char): Char {
        return 'a' + (num - '0')
    }

    private fun mapToChar(num1: Char, num2: Char): Char? {
        val sum = (num1 - '0') * 10 + (num2 - '0')
        if (sum < 26) {
            return 'a' + sum
        }
        return null
    }

    @Test
    fun test0() {
        val arr = permutation("")
        println(arr)
    }

}
